package com.hw.elasticsearch.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;

import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.MetaDataIndexTemplateService.PutListener;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.lang.UsesJava7;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hw.elasticsearch.dao.EsRepository;
import com.hw.elasticsearch.model.User;

@Controller
public class ElasticControllerRepository {
	
	@Autowired
	EsRepository es;

	@RequestMapping("putUserR")
	@ResponseBody
	public String putUser(Long id,String name,int age,String sex) {
		
		User user=new User(id,name,age,sex);
		es.save(user);
		Iterable<User> ui=es.findAll();
		StringJoiner sJoiner=new StringJoiner(";");
		ui.forEach(u->sJoiner.add(u.toString()));
		
		return sJoiner.toString();
	}
	
	@RequestMapping("putList")
	@ResponseBody
	public String putList() {
		List<User> users=new ArrayList<>();
		User user1=new User(10l, "何伟", 18, "男");
		User user2=new User(20l, "马青青", 18, "女");
		users.add(user1);
		users.add(user2);
		
		es.saveAll(users);
		
		return "success";
	}
	
	@RequestMapping("allUserR")
	@ResponseBody
	public String allUser() {
		List<User> users=new ArrayList<>();
		Iterable<User> ui=es.findAll();
		StringJoiner sJoiner=new StringJoiner(";");
		
		ui.forEach(user->sJoiner.add(user.toString()));
		return sJoiner.toString();
	}
	
	@RequestMapping("getUserR")
	@ResponseBody
	public String getUser(String name) {
		NativeSearchQueryBuilder qBuilder=new NativeSearchQueryBuilder();
		qBuilder.withQuery(QueryBuilders.matchQuery("name", name));
		
		Page<User> users=es.search(qBuilder.build());
		Long total=users.getTotalElements();
		
		StringJoiner sJoiner=new StringJoiner(";");
		
		users.forEach(user->sJoiner.add(user.toString()));
		
		return sJoiner.toString();
	}
}
